const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    newGoods: [],
    hotGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    banner: [],
    channel: [],
    swiperList: {
      autoplay: true,
      indicatorDots: true,
      interval: 5000,
      duration: 1500,
      circular: true,
    },
    tabScrollTop: 0, //离轮播图的高度
    tapupdate: false, //修改搜索框的背景色
    headerTitle: '', //头部标题
    countDay: '', //倒计时的天数
    countHour: '',
    countMinute: '',
    countSecond: '',
    endTime: 0, //倒数的总秒数
    titleImg: undefined, //标题图片
    hotNum: 0, //热销商品数量
    totalSecond: null
  },
  //扫二维码
  sweepCode: function() {
    wx.scanCode({
      success(res) {
        console.log('扫码成功')
        console.log(res)
        util.request(api.GoIndexDetail, {
          url: res.result
        }).then(data => {
          console.log('请求成功！')
          console.log(data)
          if (data.errno == 0) {
            wx.setStorageSync('info', data.data)
            wx.navigateTo({
              url: '/pages/againstCode/againstCode',
            })
          } else {
            // util.showErrorToast(data.errmsg)
            console.log('请求失败22222222！')
            wx.navigateTo({
              url: '/pages/againstFail/againstFail',
            })
          }
        })
        // wx.navigateTo({
        //   url: '/pages/test/test?path=' +res.result,
        // })
      },
      fail() {
        util.showErrorToast('扫码失败')
      }
    })
  },
  //跳转到搜索页面
  goSearch: function() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  //立即购买
  immediateBuy: function(e, param) {
    console.log('id:' + e.currentTarget.dataset.id)
    let indexGoods = this.data.hotGoods.filter(obj => {
      return obj.id == e.currentTarget.dataset.id
    })
    console.log('param:' + param)
    let hotparam = param || 'hot'
    console.log(indexGoods)
    // 检验一下库存
    if (indexGoods[0].brandId == undefined || indexGoods[0].brandId < 1) {
      util.showErrorToast('库存不足！')
      return
    }
    let goodsNum = 0
    indexGoods[0].num = goodsNum + 1
    console.log(indexGoods)
    wx.setStorageSync('cartData', indexGoods)

    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/checkout/checkout?hot=' + hotparam,
      }, 3000)
    })
  },
  // 免费兑换
  freeBuy: function(e) {
    console.log('id:' + e.currentTarget.dataset.id)
    let indexGoods = this.data.hotGoods.filter(obj => {
      return obj.id == e.currentTarget.dataset.id
    })
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo.suyongstar >= indexGoods[0].suyongstar) {
      this.immediateBuy(e, 'free')
    } else {
      let star = indexGoods[0].suyongstar - userInfo.suyongstar
      util.showErrorToast('还差' + star + '社交星' + ',分享获星')
    }
    console.log(userInfo)
  },
  // //时间倒计时
  // TimecutDown: function(that) {
  //   let currentTime = new Date().getTime() //当前时间毫秒数
  //   let endTimes = that.data.endTime //结束时间
  //   let totalSecond = endTimes - currentTime || 0
  //   // console.log('当前时间' + currentTime + '\n剩余时间：' + totalSecond + '\n结束时间：' + endTimes);
  //   if (totalSecond > 0) {
  //     let countTimes = that.formatTime(totalSecond)
  //     //渲染时钟
  //     that.setData({
  //       countDay: countTimes.totalDay,
  //       countHour: countTimes.totalHour,
  //       countMinute: countTimes.totalMinute,
  //       countSecond: countTimes.second,
  //       countTotalSecond: totalSecond
  //     })
  //     let val = setTimeout(() => {
  //       totalSecond -= 1000;
  //       that.TimecutDown(that)
  //       if (totalSecond < 0) {
  //         clearTimeout(val)
  //         util.request(api.closeCountDown).then(res => {
  //           if (res.errno == 0) {
  //             that.setData({
  //               switchOff: false
  //             })
  //           }
  //         })
  //       }
  //     }, 1000)

  //   }
  // },
  // // 时间格式化
  // formatTime: function(totalSeconds) {
  //   let totalSecond = Math.floor(totalSeconds / 1000) //总秒数
  //   let totalDay = Math.floor(totalSecond / 3600 / 24) //总天数
  //   let totalHour = Math.floor(totalSecond / 3600 % 24) //总时
  //   let totalMinute = Math.floor(totalSecond / 60 % 60) //总分
  //   let second = Math.floor(totalSecond % 60) //总秒
  //   return {
  //     totalDay,
  //     totalHour,
  //     totalMinute,
  //     second
  //   }
  // },
  onShareAppMessage: function() {
    return {
      title: '速用微商城',
      desc: '开源微信小程序商城',
      path: '/pages/index/index'
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  // 获得商品信息
  getIndexData: function() {
    let that = this;
    wx.removeStorageSync('cartData')
    util.request(api.IndexUrl).then(function(res) {
      console.log(res)
      let endTimes = that.data.endTime
      //如果显示促销时间，获取总毫秒数，如果总毫秒数不为零开始递减并保存每次递减剩下的总毫秒数，再把保存下来的总秒数当做下次递减的总毫秒数，当总毫秒数递减到零的时候隐藏促销时间并停止递减
      if (res.data.switch) {
        console.log('进入倒计时')
        endTimes = new Date().getTime() + res.data.millis
          // endTimes = new Date().getTime() + 20 * 1000
        that.setData({
          endTime: endTimes
        })
        util.timecutDown(that)
      }
      if (res.errno === 0) {
        that.setData({
          hotGoods: res.data.hotGoodsList,
          banner: res.data.banner,
          switchOff: res.data.switch,
          titleImg: res.data.footer[0].url,
          hotNum: res.data.hot,

          //  newGoods: res.data.newGoodsList,

          //  topics: res.data.topicList,
          //  brands: res.data.brandList,
          //  floorGoods: res.data.floorGoodsList,

          //  groupons: res.data.grouponList,
          //  channel: res.data.channel
        });

      }
    });
  },
  onPageScroll: function(e) { // 获取滚动条当前位置
    console.log('监听滚动条')
    let flag = false
    let title = ''
    if (e.scrollTop > this.data.tabScrollTop) {
      console.log('大于轮播图高度滚动条')
      flag = true
      title = '速用精选'
    } else {
      console.log('小于轮播图高度滚动条')
      flag = false
      title = ''
    }
    this.setData({
      tapupdate: flag,
      headerTitle: title
    })
    console.log('tapupdate:' + this.data.tapupdate)
  },
  onLoad: function(options) {

    // 页面初始化 options为页面跳转所带来的参数
    if (options.scene) {
      //这个scene的值存在则证明首页的开启来源于朋友圈分享的图,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      var scene = decodeURIComponent(options.scene);
      console.log("scene:" + scene);

      let info_arr = [];
      info_arr = scene.split(',');
      let _type = info_arr[0];
      let id = info_arr[1];

      if (_type == 'goods') {
        wx.navigateTo({
          url: '../goods/goods?id=' + id
        });
      } else if (_type == 'groupon') {
        wx.navigateTo({
          url: '../goods/goods?grouponId=' + id
        });
      } else {
        wx.navigateTo({
          url: '../index/index'
        });
      }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?grouponId=' + options.grouponId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?id=' + options.goodId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.orderId) {
      //这个orderId的值存在则证明首页的开启来源于订单模版通知,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
      });
    }

    // this.getIndexData();
  },
  onReady: function() {
    // 页面渲染完成
    let that = this
    console.log('页面渲染完成')

    let query = wx.createSelectorQuery()
    query.select('.header').boundingClientRect(function(res) {
      that.setData({
        tabScrollTop: res.bottom
      })
    })

  },
  onShow: function() {
    // 页面显示
    this.getIndexData();
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
})